<template>
  <div>
    <a-modal
      :title="type ? '新增公告' : '编辑公告'"
      :visible="visible"
      :confirmLoading="confirmLoading"
      destroyOnClose
      @cancel="cancel"
      @ok="handleOk"
    >
      <a-form
        ref="ruleForm"
        :form="form"
        :label-col="{span:4}"
        :wrapper-col="{span:19}"
        layout="horizontal"
      >
        <a-form-item label="主标题">
          <a-input
            id="title"
            v-decorator="['title',
              {
                initialValue:record.title,
                rules: [{ required: true,message:'主标题不能为空' }]
              }
            ]"
            placeholder="请输入主标题..."
          />
        </a-form-item>
        <a-form-item label="副文案" prop="content">
          <a-textarea
            :rows="4"
            v-decorator="['content',
              {
                initialValue:record.content,
                rules: [{ required: true,message:'副文案不能为空' }]
              }
            ]"
            placeholder="请输入副文案..."
          />
        </a-form-item>
        <a-form-item label="图片">
          <a-upload
            v-decorator="['gallery',
              {
                initialValue:record.gallery,
              }
            ]"
            action="/vietnam-travel-admin/configurationManagement/v1/upload-file"
            list-type="picture-card"
            :file-list="fileList"
            @preview="handlePreview"
            @change="handleChange"
            :headers="{ Authorization: getToken() }"
          >
            <div>
              <a-icon type="plus" />
              <p>最大20张</p>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="公告栏展示">
          <a-radio-group
            v-decorator="['isShow',
                {
                  initialValue:record.isShow ? 1 : 0,
                }
              ]">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="0">否</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>

      <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </a-modal>
  </div>
</template>

<script>
import { getBase64, imagesList } from '@/utils/util'
import { saveRequest, updateRequest } from '@/api/notice-manage'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { message } from 'ant-design-vue'

export default {
  name: 'noticeEditAdd',
  props: ['visible', 'record', 'type'],
  data() {
    return {
      form: this.$form.createForm(this),
      confirmLoading: false,
      modalVisible: false,
      previewVisible: false,
      previewImage: '',
      fileList: []
    }
  },
  watch: {
    visible(val) {
      this.modalVisible = val
      this.init()
    }
  },
  beforeMount() {
    this.init()
  },
  methods: {
    init() {
      this.$nextTick(() => {
        this.fileList = this.record?.gallery?.map((item, index) => {
          return {
            uid: '-1' + index,
            name: '',
            status: 'done',
            sort: index + 1,
            confId: item.confId,
            url: item.url
          }
        })
      })
    },
    getToken,
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          // 集合图片处理
          const images = imagesList(this.fileList)
          this.confirmLoading = true
          const params = {
            content: values.content,
            gallery: images,
            isShow: values.isShow ? 1 : 0,
            title: values.title,
            userId: store.getters.userInfo?.userId
          }
          // 如果是修改需要新增这两个参数
          if (!this.type) {
            params.id = this.record.id
            params.uuid = this.record.uuid
          }
          let api = this.type ? saveRequest : updateRequest
          api(params).then(res => {
            this.confirmLoading = false
            if (res.code === 200) {
              message.success(res.msg || '操作成功！')
              this.$emit('onOk', this.type ? 'add' : 'edit')
            }
          })
        }
      })
    },
    cancel() {
      this.resetFormValue()
      this.$emit('cancel')
    },
    // 重置表单一般在第一次访问表单时进行重置
    resetFormValue() {
      this.$nextTick(() => {
        this.form.resetFields()
      })
    },
    handleCancel() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange(info) {
      console.log(info)
      if (info.file.url) {
        this.fileList = info.fileList
        return
      }
      if (!info?.file?.type.startsWith('image/')) {
        this.$message.error('只能上传图片')
        return false
      }
      const isLt2M = info?.file?.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('最大只能上传2MB的图片，请压缩图片后再试!')
        return isLt2M
      }
      if (info.fileList && info.fileList?.length > 20) {
        this.$message.error('最多只能上传20张!')
        return false
      }
      this.fileList = info.fileList
    }
  }
}
</script>

<style scoped lang="less">

</style>